package com.tea.servlet;

import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.tea.service.AdminService;
import com.tea.service.UserService;
import com.tea.service.impl.AdminServiceImpl;
import com.tea.service.impl.UserServiceImpl;
import com.tea.entity.User;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private AdminService adminService = new AdminServiceImpl();
    private UserService userService = new UserServiceImpl();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 转发到登录页面
        request.getRequestDispatcher("/login.jsp").forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        
        // 管理员登录验证
        if (adminService.validate(username, password)) {
            HttpSession session = request.getSession();
            session.setAttribute("role", "admin");
            session.setAttribute("username", username);
            response.sendRedirect("admin-dashboard.jsp");
            return;
        }
        
        // 普通用户登录验证
        User user = null;
        try {
            user = userService.login(username, password);
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("errorMsg", "数据库错误，请稍后再试");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }
        if (user != null) {
            HttpSession session = request.getSession();
            session.setAttribute("role", "user");
            session.setAttribute("username", username);
            session.setAttribute("user", user);
            response.sendRedirect("index.jsp");
            return;
        }
        
        // 登录失败
        request.setAttribute("errorMsg", "用户名或密码错误");
        request.getRequestDispatcher("/login.jsp").forward(request, response);
    }
}